package com.guomei.service.curse.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guomei.bean.User;
import com.guomei.bean.curse.AuthorizeChannelCode;
import com.guomei.bean.curse.Channel;
import com.guomei.mapper.UserMapper;
import com.guomei.mapper.curse.ChannelMapper;
import com.guomei.service.curse.ChannelService;
import com.guomei.utils.PageData;
import com.guomei.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 渠道服务实现类
 */
@Service
@Slf4j
@Transactional
public class ChannelServiceImpl implements ChannelService {
    
    @Resource
    private ChannelMapper channelMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Channel getById(Long id) {
        if (id == null) {
            return null;
        }
        return channelMapper.selectById(id);
    }

    @Override
    public List<Channel> getAll() {
        return channelMapper.selectAll();
    }

    @Override
    public Result<?> getByCondition(Channel channel) {
        PageHelper.startPage(channel.getPageNum(), channel.getPageSize());
        List<Channel> channels = channelMapper.selectByCondition(channel);
        // 封装分页结果到PageData
        PageData<Channel> pageData = new PageData<>();
        PageInfo<Channel> pageInfo = new PageInfo<>(channels);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(channel.getPageNum());
        pageData.setPageSize(channel.getPageSize());
        return Result.success(pageData);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(Channel channel) {
        if (channel == null) {
            return false;
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        channel.setCreatedTime(now);
        channel.setUpdatedTime(now);
        
        // 设置默认值
        if (channel.getStatus() == null) {
            channel.setStatus((short) 1); // 默认启用
        }
        if (channel.getSortOrder() == null) {
            channel.setSortOrder(0);
        }
        if (channel.getChannelSecret() == null) {
            channel.setChannelSecret(generateChannelSecret());
        }

        return channelMapper.insert(channel) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSave(List<Channel> channels) {
        if (channels == null || channels.isEmpty()) {
            return false;
        }

        LocalDateTime now = LocalDateTime.now();
        for (Channel channel : channels) {
            // 设置创建和更新时间
            channel.setCreatedTime(now);
            channel.setUpdatedTime(now);
            
            // 设置默认值
            if (channel.getStatus() == null) {
                channel.setStatus((short) 1); // 默认启用
            }
            if (channel.getSortOrder() == null) {
                channel.setSortOrder(0);
            }
            if (channel.getChannelSecret() == null) {
                channel.setChannelSecret(generateChannelSecret());
            }
        }

        return channelMapper.batchInsert(channels) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(Channel channel) {
        if (channel == null || channel.getId() == null) {
            return false;
        }

        // 更新时间设为当前时间
        channel.setUpdatedTime(LocalDateTime.now());

        return channelMapper.updateById(channel) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Long id) {
        if (id == null) {
            return false;
        }
        return channelMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchRemove(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        return channelMapper.batchDelete(ids) > 0;
    }

    @Override
    public Channel getByChannelCode(String channelCode) {
        if (channelCode == null) {
            return null;
        }
        return channelMapper.selectByChannelCode(channelCode);
    }

    @Override
    public Channel getByChannelSecret(String channelSecret) {
        if (channelSecret == null) {
            return null;
        }
        return channelMapper.selectByChannelSecret(channelSecret);
    }

    @Override
    public List<Channel> getByStatus(Short status) {
        if (status == null) {
            return null;
        }
        return channelMapper.selectByStatus(status);
    }

    @Override
    public String generateChannelSecret() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 32).toUpperCase();
    }

    @Override
    public boolean validateChannelSecret(String channelSecret) {
        if (channelSecret == null) {
            return false;
        }
        Channel channel = getByChannelSecret(channelSecret);
        return channel != null && channel.getStatus() != null && channel.getStatus() == 1;
    }

    @Override
    public Result<?> authorizeChannelCode(AuthorizeChannelCode authorizeChannelCode) {
        Channel channel = channelMapper.selectByChannelCode(authorizeChannelCode.getChannelCode());
        if (channel != null && channel.getStatus() != null && channel.getStatus() == 1) {
            User user = new User();
            user.setChannelCode(authorizeChannelCode.getChannelCode());
            user.setId(authorizeChannelCode.getUserId());
            int update = userMapper.update(user);
            return update > 0 ? Result.success("授权渠道码成功") : Result.fail("授权渠道码失败");
        } else {
            return Result.fail("渠道不存在或已禁用");
        }
    }
}
